<template>
  <el-table :data="props.tableData" class="table" border show-overflow-tooltip style="margin-top: 30px;">
    <el-table-column type="index" width="50"/>
    <el-table-column prop="username" label="姓名"/>
    <el-table-column prop="email" label="邮箱"/>
    <el-table-column prop="mobile" label="电话" />
    <el-table-column prop="role_name" label="角色" />
    <el-table-column label="状态" width="80">
      <template #default="scope">
        <el-switch v-model="scope.row.mg_state" @click="changeSwitch(scope.row)"/>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="180">
      <template #default="scopeB">
        <el-button size="small" color="#409eff" :icon="Edit" style="color: #fff" @click="emit('showDialog', true, 'edit', scopeB.row.id)"></el-button>
        <el-button size="small" color="#F56C6C" :icon="Delete" style="color: #fff" @click="deleteUser(scopeB.row.id)"></el-button>
        <el-button size="small" color="#E6A23C" :icon="Setting" style="color: #fff" @click="emit('showGiveRoleDialog', true, scopeB.row.id, scopeB.row.username, scopeB.row.role_name)"></el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script lang="ts" setup>
import { Edit, Delete, Setting } from '@element-plus/icons-vue'
import { ChangeSwitchFnc, RemoveUserFnc } from '@/api/user'

const props = defineProps({
  tableData: {type: Array, required: true},
  total: {type: Number, required: true},
  pageNow: {type: Number, required: true},
  pageSize: {type: Number, required: true}
})


const emit = defineEmits(['showDialog', 'init', 'showGiveRoleDialog'])

// switch 改变状态
const changeSwitch = async (row: {id: number, mg_state: boolean}) => {
  const res = await ChangeSwitchFnc({ id: row.id, state: row.mg_state })
  if(res.data.meta.status === 200) ElMessage({type: 'success', message: res.data.meta.msg, duration: 1000})
}

// 删除用户
const deleteUser = (id: number) => {
  // const res = await RemoveUserFnc(id)
  ElMessageBox.confirm('此操作将永久删除用户, 是否继续?', '提示',{ confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'}).then(async () => {
    const res = await RemoveUserFnc(id)
    if(res.data.meta.status === 200) {
      ElMessage({type: 'success', message: '删除成功', duration: 1000, onClose: () => {
        emit('init', props.pageNow, props.pageSize)
      }}) 
    }
  }).catch(() => {
    ElMessage({ type: 'info', message: '取消删除'})
  })
}
</script>